package com.jinxi.web.filter;

import com.jinxi.web.config.WebConstants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;

public class WebSessionFilter implements Filter {
    private static HashSet<String> exclude_url = new HashSet<>();

    static {
        exclude_url.add("/");
        exclude_url.add("/index.html");
        exclude_url.add("/index.htm");
        exclude_url.add("/index.jsp");
        exclude_url.add("/login");
    }

    private boolean isExclude(String path) {
        if (exclude_url.contains(path)) {
            return true;
        }

        return false;
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession();
        String user = (String) session.getAttribute(WebConstants.session_user_name);
        if (null != user) {
            chain.doFilter(request, response);
            return;
        } else {
            String url = req.getRequestURI().toString();
            if (isExclude(url)) {
                chain.doFilter(request, response);
                return;
            }
            resp.sendRedirect(WebConstants.login_page_action);
            return;
        }
    }

    public void init(FilterConfig fConfig) throws ServletException {

    }


}
